﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="login.aspx.cs" company="VDC-IT" author="LONGLC">
//   login page code behind
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace VDC.VONE.WEB
{
    #region

    using System;
    using System.Data.SqlClient;
    using System.Reflection;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;

    using AdCom.Utility;

    using VDC.COMMON;
    using VDC.COMMON.ExceptionHelpers;
    using VDC.VONE.BLL;
    using VDC.VONE.ENTITIES;

    #endregion

    /// <summary>
    ///     The login.
    /// </summary>
    public partial class Login : Flesk.Accelerator.Page
    {
        #region Constants

        /// <summary>
        ///     The aspnetsql membership provider
        /// </summary>
        private const string AspnetsqlMembershipProvider = "AspNetSqlMembershipProvider";

        /// <summary>
        ///     The browser param.
        /// </summary>
        private const string BrowserParam = "@Browser";

        /// <summary>
        ///     The captcha session name.
        /// </summary>
        private const string CaptchaSessionName = "CaptchaImageText";

        /// <summary>
        ///     The ip address param.
        /// </summary>
        private const string IpAddressParam = "@IpAddress";

        /// <summary>
        ///     The platform param.
        /// </summary>
        private const string PlatformParam = "@PlatForm";

        /// <summary>
        ///     The stored procedure to call.
        /// </summary>
        private const string StoredProcedureToCall = "AdStore_SiteLog_INSERT";

        /// <summary>
        ///     The user name param.
        /// </summary>
        private const string UserNameParam = "@AdComUserName";

        /// <summary>
        /// The aspnetadmembershipprovider
        /// </summary>
        private const string AspnetADmembershipprovider = "AspNetADMembershipProvider";

        /// <summary>
        /// The default aspx
        /// </summary>
        private const string DefaultAspx = "~/default.aspx";

        /// <summary>
        /// The slash
        /// </summary>
        private const string Slash = "%2f";

        /// <summary>
        /// The return URL
        /// </summary>
        private readonly string returnUrl = HtmlHelper.GetRequestString("ReturnUrl", "~/default.aspx");

        #endregion

        #region Methods

        /// <summary>
        /// The imb submit_ click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void ImbSubmitClick(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                this.LoginAction();
                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.Message);
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// The page_ load.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void Page_Load(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                this.lbError.Text = string.Empty;

                if (this.Page.User.Identity.IsAuthenticated)
                {
                    this.Response.Redirect(this.returnUrl, false);
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                }

                ////if (!Page.IsPostBack)
                ////{
                ////    this.ClearCookieAndSignOut();
                ////}

                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.Message);
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// Clears the cookie and sign out.
        /// </summary>
        private void ClearCookieAndSignOut()
        {
            if (this.Session[Constants.SessionKey.CurrentUserId] != null)
            {
                this.Session.Abandon();
                this.Session.Clear();
            }

            string[] myCookies = this.Request.Cookies.AllKeys;
            foreach (string cookie in myCookies)
            {
                var httpCookie = this.Response.Cookies[cookie];
                if (httpCookie != null)
                {
                    httpCookie.Expires = DateTime.Now.AddDays(-1);
                }
            }

            FormsAuthentication.SignOut();
        }

        /// <summary>
        /// The log login db.
        /// </summary>
        /// <param name="strUserName">
        /// The str user name.
        /// </param>
        private void LogLoginDB(string strUserName)
        {
            var helper = new AdGetBrowserHelper();
            new AdSqlDataLocalHelper().CallActionStoredProcedure(
                StoredProcedureToCall,
                new[] { new SqlParameter(UserNameParam, strUserName), new SqlParameter(BrowserParam, helper.GetBrowser), new SqlParameter(PlatformParam, helper.GetPlatform), new SqlParameter(IpAddressParam, helper.GetIpAddress) });
        }

        /// <summary>
        /// The login action.
        /// </summary>
        private void LoginAction()
        {
            if (this.Session[CaptchaSessionName] != null)
            {
                int result = string.Compare(this.txtCaptcha.Text.Trim(), this.Session[CaptchaSessionName].ToString(), System.StringComparison.OrdinalIgnoreCase);
                if (this.Page.IsValid && result == 0)
                {
                    this.lbError.Text = string.Empty;
                    string strUserName = this.txtUserName.Text.Trim();
                    string strPassword = this.txtPassword.Text.Trim();

                    if (this.ValidInfo(strUserName, strPassword))
                    {
                        return;
                    }

                    ConfigService configService = new ConfigService();
                    MembershipProvider membershipProvider = Membership.Providers[AspnetsqlMembershipProvider];

                    if (membershipProvider != null)
                    {
                        MembershipUser mu = membershipProvider.GetUser(this.txtUserName.Text.Trim(), true);
                        ////mu.UnlockUser();
                        ////mu.ChangePassword(mu.ResetPassword(), "123456");

                        if (mu != null)
                        {
                            if (!mu.IsApproved)
                            {
                                this.lbError.Text = Resource.Login_ImbSubmitClick_AccLock;

                                ////Resource.Login_ImbSubmitClick_AccLock;
                            }
                            else if (mu.IsLockedOut)
                            {
                                this.lbError.Text = Resource.Login_ImbSubmitClick_AccLock;
                            }
                            else
                            {
                                if (configService.GetDefaultConfig() == Constants.Config.Sql)
                                {
                                    this.ValidateOnSql(membershipProvider, strUserName, strPassword);
                                }
                                else if (configService.GetDefaultConfig() == Constants.Config.Ldap)
                                {
                                    ////validte user on AD
                                    this.ValidateOnAd(strUserName, strPassword);
                                }
                            }
                        }
                        else
                        {
                            this.lbError.Text = PublicFuncs.GetMessage(Messages.LoginNoExistAcc);

                            ////Resource.Login_ImbSubmitClick_NoExistAcc;
                        }
                    }
                }
                else
                {
                    this.lbError.Text = PublicFuncs.GetMessage(Messages.LoginWrongCaptcha);

                    ////Resource.Login_ImbSubmitClick_WrongCaptcha;
                }
            }
            else
            {
                this.lbError.Text = Resource.Login_LoginAction_AgainLogin;
            }
        }

        /// <summary>
        /// The valid info.
        /// </summary>
        /// <param name="strUserName">
        /// The str user name.
        /// </param>
        /// <param name="strPassword">
        /// The str password.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        private bool ValidInfo(string strUserName, string strPassword)
        {
            if (strUserName == string.Empty)
            {
                this.lbError.Text = PublicFuncs.GetMessage(Messages.LoginNoName);

                ////Resource.Login_ImbSubmitClick_NoName;
                this.txtUserName.Focus();
                return true;
            }

            if (strPassword == string.Empty)
            {
                this.lbError.Text = PublicFuncs.GetMessage(Messages.LoginNoPassword);

                ////Resource.Login_ImbSubmitClick_NoPassword;
                this.txtPassword.Focus();
                return true;
            }

            return false;
        }

        /// <summary>
        /// The validate on ad.
        /// </summary>
        /// <param name="strUserName">
        /// The str user name.
        /// </param>
        /// <param name="strPassword">
        /// The str password.
        /// </param>
        private void ValidateOnAd(string strUserName, string strPassword)
        {
            MembershipProvider membershipAdProvider = Membership.Providers[AspnetADmembershipprovider];
            if (membershipAdProvider != null)
            {
                bool blnIsMemberShip = membershipAdProvider.ValidateUser(strUserName, strPassword);
                if (blnIsMemberShip)
                {
                    FormsAuthentication.SetAuthCookie(strUserName, false);
                    this.LogLoginDB(strUserName);
                    Response.Redirect(this.returnUrl, false);
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                }
                else
                {
                    this.lbError.Text = PublicFuncs.GetMessage(Messages.LoginWrongPass);

                    ////Resource.Login_ImbSubmitClick_WrongPass;
                }
            }
            else
            {
                this.lbError.Text = Resource.Login_ValidateOnAd_No_Exist_On_AD_;
            }
        }

        /// <summary>
        /// The validate on sql.
        /// </summary>
        /// <param name="membershipProvider">
        /// The membership provider.
        /// </param>
        /// <param name="strUserName">
        /// The str user name.
        /// </param>
        /// <param name="strPassword">
        /// The str password.
        /// </param>
        private void ValidateOnSql(MembershipProvider membershipProvider, string strUserName, string strPassword)
        {
            bool blnIsMemberShip = membershipProvider.ValidateUser(strUserName, strPassword);
            if (blnIsMemberShip)
            {
                FormsAuthentication.SetAuthCookie(strUserName, false);
                this.LogLoginDB(strUserName);
                Response.Redirect(this.returnUrl, false);
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            else
            {
                this.lbError.Text = PublicFuncs.GetMessage(Messages.LoginWrongPass);

                ////Resource.Login_ImbSubmitClick_WrongPass;
            }
        }

        #endregion
    }
}